package server

import (
	"common/database/config"
	"context"
	"errors"
	"test_paper_srv/internal/models/dao"
	pb "test_paper_srv/proto"
	"time"
)

type Server struct {
	pb.UnimplementedPaperServer
}

func (c *Server) CreatePaper(ctx context.Context, request *pb.CreatePaperRequest) (*pb.CreatePaperResponse, error) {
	paper := dao.TestPaper{
		UserId:        int(request.UserId),
		TestPaperName: request.TestPaperName,
		ClassName:     request.ClassName,
		CreateTime:    time.Now(),
	}
	db := config.DB.Begin()
	err := db.Create(&paper).Error
	if err != nil {
		db.Rollback()
		return nil, errors.New("试卷创建失败")
	}
	for _, i := range request.QuestionId {
		paperQuestion := dao.TestPaperQuestion{
			TestPaperId: int(paper.ID),
			QuestionId:  int(i),
		}
		err = db.Create(&paperQuestion).Error
		if err != nil {
			db.Rollback()
			return nil, errors.New("试卷创建失败")
		}
	}
	db.Commit()
	return &pb.CreatePaperResponse{Id: int64(paper.ID)}, nil
}

func (c *Server) UpdatePaper(ctx context.Context, request *pb.UpdatePaperRequest) (*pb.UpdatePaperResponse, error) {
	var paper *dao.TestPaper
	config.DB.Model(&dao.TestPaper{}).Where("id=?", request.PaperId).Find(&paper).Limit(1)
	papers := dao.TestPaper{
		UserId:        int(request.UserId),
		TestPaperName: request.TestPaperName,
		ClassName:     request.ClassName,
		CreateTime:    time.Now(),
	}
	err := config.DB.Model(&dao.TestPaper{}).Where("id=?", request.PaperId).Updates(&papers).Error
	if err != nil {
		return nil, errors.New("修改试卷失败")
	}
	paperQuestion := dao.TestPaperQuestion{
		TestPaperId: int(paper.ID),
		QuestionId:  int(request.QuestionId),
	}
	err = config.DB.Where("test_paper_id=? and question_id=?", request.PaperId, request.OldQuestionId).Updates(&paperQuestion).Error
	if err != nil {
		return nil, errors.New("修改试卷题目失败")
	}
	return &pb.UpdatePaperResponse{}, nil
}

func (c *Server) DeletePaper(ctx context.Context, request *pb.DeletePaperRequest) (*pb.DeletePaperResponse, error) {
	err := config.DB.Where("id=?", request.PaperId).Delete(&dao.TestPaper{}).Error
	if err != nil {
		return nil, errors.New("试卷删除失败")
	}
	err = config.DB.Where("test_paper_id=?", request.PaperId).Delete(&dao.TestPaperQuestion{}).Error
	if err != nil {
		return nil, errors.New("试卷题目删除失败")
	}
	return &pb.DeletePaperResponse{}, nil
}
